package com.sxt.aspect;

import com.sxt.domain.GoodsType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;


@Aspect
@EnableAspectJAutoProxy
@Component
public class GoodsTypeCacheAspect {

    private Log log= LogFactory.getLog(GoodsTypeCacheAspect.class);


    private static Map<String,Object> cacheContainer=new HashMap<>();

    public static final String EXECUTION="execution(* com.sxt.service.impl.GoodsTypeServiceImpl.getById(..))";


    private static final String PROFIX="goodstype:";


    @Around(value = EXECUTION)
    public Object cacheGoodsType(ProceedingJoinPoint pj) throws Throwable {
        //取到查询的ID
        Serializable arg = (Serializable) pj.getArgs()[0];
        //从缓存里面查询
        String key=PROFIX+arg;

        Object obj = cacheContainer.get(key);

        if(null!=obj){
            log.info("从缓存里面找到key="+key+"的对象");
            return obj;
        }else{
            log.info("从缓存里面没有到找到key="+key+"的对象  去查询数据库 并放入缓存容器");
            GoodsType type = (GoodsType) pj.proceed();
            cacheContainer.put(PROFIX+type.getTypeId(),type);
            return type;
        }

    }





}
